package com.distributeredis.redis_springboot.springapachehttpclienthttpconnectionresttemplate.httpclient.study4.controller;

import com.alibaba.fastjson2.JSON;
import com.distributeredis.redis_springboot.springapachehttpclienthttpconnectionresttemplate.httpclient.study4.entity.Weather;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/httpclient")
@Slf4j
public class TianXingApiHttpClientController {
    /**
     * 使用  HttpClient get和post请求第三方天行api
     *
     * @return
     */
    @GetMapping("/test")
    public Object test1(@RequestParam Map<String, String> map) throws Exception {
        String RequestData = "";  // 结果
        // 创建HttpClient对象
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = null;
        try{
            // 拼接参数，可以用URIBuilder，也可以直接拼接在？传值，拼在url后面，  uri+"?id=123"  方式一
//            URIBuilder uriBuilder = new URIBuilder("https://apis.tianapi.com/tianqi/index?key=4556c57375b2fcda12f6fc50f8570558&city="+URLEncoder.encode("东莞","UTF-8")+"&type=1");
            URIBuilder uriBuilder = new URIBuilder("https://apis.tianapi.com/tianqi/index");
            // 方式二  设置get参数  说一下不同(setParameter会覆盖同名参数的值，addParameter则不会)
//            uriBuilder.addParameter("key","4556c57375b2fcda12f6fc50f8570558");
//            uriBuilder.addParameter("city","周口");
//            uriBuilder.addParameter("type","1");
            // 方式三  设置get参数
            List<NameValuePair> list = new LinkedList<>();
            BasicNameValuePair param1 = new BasicNameValuePair("key","4556c57375b2fcda12f6fc50f8570558");
            BasicNameValuePair param2 = new BasicNameValuePair("city","平顶山");
            BasicNameValuePair param3 = new BasicNameValuePair("type","1");

            list.add(param1);
            list.add(param2);
            list.add(param3);
            uriBuilder.setParameters(list);

            URI uri = uriBuilder.build();

            // 创建get请求
            httpGet = new HttpGet(uri);

            /*
             * 添加请求头信息
             */
            // 浏览器表示
            httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
            // 传输的类型
            httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded");
            httpGet.addHeader("Referer", "https://www.tianapi.com/apiview/72");

            HttpResponse response = httpClient.execute(httpGet);
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {   // 200请求成功
                // 结果返回
                RequestData = EntityUtils.toString(response.getEntity(),StandardCharsets.UTF_8);
            }
        }catch (Exception e) {
            log.info("请求失败！");
        }finally {
            // 释放连接
            if(httpGet != null) {
                httpGet.releaseConnection();
            }
        }
        return RequestData;
    }
    @GetMapping("/test2")
    public Object test2(@RequestParam Map<String, String> map) throws Exception {
        String RequestData = "";  // 结果

        //httpclient: 设置连接池及超时配置，请求数据:PoolingHttpClientConnectionManager
        //httpclient连接池
        //创建连接池
        PoolingHttpClientConnectionManager cManager = new PoolingHttpClientConnectionManager();
        //设置最大连接数
        cManager.setMaxTotal(50);
        //设置每个主机地址的并发数
        cManager.setDefaultMaxPerRoute(20);

        // 创建HttpClient对象
        HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(cManager).build();
        HttpGet httpGet = null;
        try{
            // 拼接参数，可以用URIBuilder，也可以直接拼接在？传值，拼在url后面，  uri+"?id=123"  方式一
//            URIBuilder uriBuilder = new URIBuilder("https://apis.tianapi.com/tianqi/index?key=4556c57375b2fcda12f6fc50f8570558&city="+URLEncoder.encode("东莞","UTF-8")+"&type=1");
            URIBuilder uriBuilder = new URIBuilder("https://apis.tianapi.com/tianqi/index");
            // 方式二  设置get参数  说一下不同(setParameter会覆盖同名参数的值，addParameter则不会)
//            uriBuilder.addParameter("key","4556c57375b2fcda12f6fc50f8570558");
//            uriBuilder.addParameter("city","周口");
//            uriBuilder.addParameter("type","1");
            // 方式三  设置get参数
            List<NameValuePair> list = new LinkedList<>();
            BasicNameValuePair param1 = new BasicNameValuePair("key","4556c57375b2fcda12f6fc50f8570558");
            BasicNameValuePair param2 = new BasicNameValuePair("city","洛阳");
            BasicNameValuePair param3 = new BasicNameValuePair("type","1");

            list.add(param1);
            list.add(param2);
            list.add(param3);
            uriBuilder.setParameters(list);

            URI uri = uriBuilder.build();

            // 创建get请求
            httpGet = new HttpGet(uri);

            //设置请求参数
            RequestConfig config = RequestConfig.custom().setConnectTimeout(50000) //连接超时时间
                    .setConnectionRequestTimeout(5000) //从线程池中获取线程超时时间
                    .setSocketTimeout(80000) //设置数据超时时间
                    .build();

            httpGet.setConfig(config);

            /*
             * 添加请求头信息
             */
            // 浏览器表示
            httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
            // 传输的类型
            httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded");
            httpGet.addHeader("Referer", "https://www.tianapi.com/apiview/72");
            httpGet.addHeader("Connection", "keep-alive");

            HttpResponse response = httpClient.execute(httpGet);
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {   // 200请求成功
                // 结果返回
                RequestData = EntityUtils.toString(response.getEntity(),StandardCharsets.UTF_8);
            }
        }catch (Exception e) {
            log.info("请求失败！");
        }finally {
            // 释放连接
            if(httpGet != null) {
                httpGet.releaseConnection();
            }
        }
        return RequestData;
    }
    // post方式
    @PostMapping("/test4")
    public Object test4(@RequestBody Map<String, String> map) throws Exception {
        String responseData = "";
        String path = "https://apis.tianapi.com/tianqi/index";
        // 创建httpclient对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(path);
        try{
            // 参数键值对
            List<NameValuePair> pairs = new ArrayList<>();
            NameValuePair pair1 = new BasicNameValuePair("key","4556c57375b2fcda12f6fc50f8570558");
            NameValuePair pair2 = new BasicNameValuePair("city","周口");
            NameValuePair pair3 = new BasicNameValuePair("type","1");

            pairs.add(pair1);
            pairs.add(pair2);
            pairs.add(pair3);

            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,StandardCharsets.UTF_8);
            httpPost.setEntity(entity);

            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.setHeader("Referer", "https://www.tianapi.com");
            httpPost.setHeader("Connection", "keep-alive");

            CloseableHttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                responseData = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            }
        }catch (Exception e) {
            System.out.println("error");
        }finally {
            httpPost.releaseConnection();
        }
        return responseData;
    }

    // post方式   发送json字符串
    @PostMapping("/test5")
    public Object test5(@RequestBody Map<String, String> map) throws Exception {
        String responseData = "";
        String path = "http://localhost:8080/httpclient/testjson";
        // 创建httpclient对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(path);
        try{
            httpPost.addHeader("Content-type","application/json;charset=utf-8");
            httpPost.addHeader("Connection","keep-alive");
            httpPost.addHeader("Accept","application/json");

            String params = "{\"key\": \"4556c57375b2fcda12f6fc50f8570558\",\"city\": \"101020100\",\"type\": \"1\"}";
            httpPost.setEntity(new StringEntity(params, StandardCharsets.UTF_8));

            CloseableHttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                responseData = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            }
        }catch (Exception e) {
            System.out.println("error");
        }finally {
            httpPost.releaseConnection();
        }
        return responseData;
    }

    // 测试使用  post传参json字符串格式
    @PostMapping("/testjson")
    public Object testjson(@RequestBody Map<String,String> map) {
        System.out.println(map);
        String testData = "{\n" +
                "  \"code\": 200,\n" +
                "  \"msg\": \"success\",\n" +
                "  \"result\": {\n" +
                "    \"date\": \"2023-12-30\",\n" +
                "    \"week\": \"星期六\",\n" +
                "    \"province\": \"河南\",\n" +
                "    \"area\": \"郑州\",\n" +
                "    \"areaid\": \"101180101\",\n" +
                "    \"weather\": \"晴\",\n" +
                "    \"weatherimg\": \"qing.png\",\n" +
                "    \"weathercode\": \"qing\",\n" +
                "    \"real\": \"13.9℃\",\n" +
                "    \"lowest\": \"-2℃\",\n" +
                "    \"highest\": \"14℃\",\n" +
                "    \"wind\": \"西风\",\n" +
                "    \"windspeed\": \"12\",\n" +
                "    \"windsc\": \"3级\",\n" +
                "    \"sunrise\": \"07:32\",\n" +
                "    \"sunset\": \"17:23\",\n" +
                "    \"moonrise\": \"\",\n" +
                "    \"moondown\": \"\",\n" +
                "    \"pcpn\": \"0\",\n" +
                "    \"uv_index\": \"0\",\n" +
                "    \"aqi\": \"124\",\n" +
                "    \"quality\": \"轻度\",\n" +
                "    \"vis\": \"8\",\n" +
                "    \"humidity\": \"25\",\n" +
                "    \"alarmlist\": [],\n" +
                "    \"tips\": \"冬季晴天需注意保湿，外出避免长时间紫外线照射。该地区今日温差较大，建议根据实际情况适时调整衣着安排。天气寒冷，请注意防寒保暖。建议着装：棉衣、羽绒服、冬大衣、皮夹克加羊毛衫、厚呢外套、呢帽、手套等；年老体弱者尽量少外出。空气质量较差，敏感人群建议减少体力消耗类户外活动。\"\n" +
                "  }\n" +
                "}";
        return JSON.parseObject(testData, Weather.class);
    }
}
